import Paho from 'paho-mqtt'
import { useUserStore } from '@/store/user'
import config from '@/global/config'

// const str = 'T/V2X/035/RSM'
const str_RSM = `V2X/${config.CLIENT_ID}/RSM`
const str_PASS_INFO = `V2X/${config.CLIENT_ID}/PASS_INFO`

const initMqtt = (item) => {
  const userStore = useUserStore()
  const ip = config.apiTiannetWSConfig.url
  const port = config.apiTiannetWSConfig.port
  const newClientId = item + '$' + parseInt(Math.random()*(99999999-10000000)+10000000)
  const client = new Paho.Client(ip, Number(port), newClientId)
  client.connect({
    onSuccess: () => {
      // if (item === 'V2X/035/#') {
        client.subscribe([str_RSM, str_PASS_INFO])
        // client.subscribe('V2X/123/RSM')

      // }
    },
    userName: 'tianan',
    password: 'tianan'
  })
  client.onMessageArrived = (message) => {
    // console.log(message)
    switch (message.topic) {
      case str_RSM: { // 车辆数据
        // console.log(message)
        userStore.setVehicleData(JSON.parse(message.payloadString))
        break
      } 
      case str_PASS_INFO: {
        // console.log(message)
        userStore.setPerceptionObject(JSON.parse(message.payloadString))
      }
      default:
    }
  }
  return client
}

export {
  initMqtt
}